package com.lovemanai.taglib;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * 自定义标签中使用属性
 * @author lovemanai
 *
 */
public class QueryTag extends SimpleTagSupport{

	//定义成员变量代表标签的属性
	private String driver;
	private String url;
	private String username;
	private String password;
	private String sql;
	//数据库访问对象
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private ResultSetMetaData rsm = null;
	
	
	
	public String getDriver() {
		return driver;
	}



	public void setDriver(String driver) {
		this.driver = driver;
	}



	public String getUrl() {
		return url;
	}



	public void setUrl(String url) {
		this.url = url;
	}



	public String getUsername() {
		return username;
	}



	public void setUsername(String username) {
		this.username = username;
	}



	public String getPassword() {
		return password;
	}



	public void setPassword(String password) {
		this.password = password;
	}


	

	public String getSql() {
		return sql;
	}



	public void setSql(String sql) {
		this.sql = sql;
	}



	public Connection getConn() {
		return conn;
	}



	public void setConn(Connection conn) {
		this.conn = conn;
	}



	public Statement getStmt() {
		return stmt;
	}



	public void setStmt(Statement stmt) {
		this.stmt = stmt;
	}



	public ResultSet getRs() {
		return rs;
	}



	public void setRs(ResultSet rs) {
		this.rs = rs;
	}



	public ResultSetMetaData getRsm() {
		return rsm;
	}



	public void setRsm(ResultSetMetaData rsm) {
		this.rsm = rsm;
	}



	@Override
	public void doTag() throws JspException, IOException {
		try {
			//注册驱动
			Class.forName(driver);
			//获得Connection对象
			conn = DriverManager.getConnection(url, username, password);
			//创建Statement对象
			stmt = conn.createStatement();
			//执行查询
			rs = stmt.executeQuery(sql);
			rsm = rs.getMetaData();
			//获取列数
			int col = rsm.getColumnCount();
			System.out.println(col);
			//获取页面输出流
			Writer out = getJspContext().getOut();
			//在页面输出表格
			out.write("<table border='1px' bgcolor='#999999' width='400'>");
			//遍历结果集
			while(rs.next()) {
				out.write("<tr>");
				
				//循环输出查询到的数据
				for(int i = 1; i <= col; i++) {
					out.write("<td>");
					out.write(rs.getString(i));
					out.write("</td>");
				}
				out.write("</tr>");
			}
			
			out.write("</table>");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	
}

